#include <vector>
using namespace std;


// version 1
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int left = 0, right = 0;
        int retlen = 0, sum = 0;
        while(right <= nums.size()){
            while(sum < target){
               if(right < nums.size()) sum += nums[right];
               ++right;
               if(right > nums.size()) break;
            }
            if(sum >= target)
                retlen = (retlen == 0 || (right - left) < retlen) ? right - left : retlen;
            if(left < nums.size()) sum -= nums[left++];
        }    
        return retlen;
    }
};


//这种写法更好一点！
class Solution2 {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int n = nums.size();
        int sum = 0, retlen = 0;
        for(int left = 0, right = 0; right < n; ++right){
            //入窗口
            sum += nums[right];
            while(sum >= target){
                //只要窗口内数据满足要求，就一直缩小窗口
                int sublen = right - left + 1;
                retlen = (retlen == 0 || sublen < retlen) ? sublen : retlen;
                sum -= nums[left++];
            }
        }
        return retlen;
    }
};